<template>
  <div class="container" v-loading.fullscreen.lock="fullscreenLoading">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>运行管理</el-breadcrumb-item>
      <el-breadcrumb-item>工作质量反馈</el-breadcrumb-item>
      <el-breadcrumb-item>排班管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ programme }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="tableColumns">
      <el-form ref="mainForm" :rules="rules" label-width="120px" :inline="false" :model="ruleForm.mainForm"
               class="demo-form-inline">
        <div class="content">
          <el-row>
            <el-col :span="12">
              <el-form-item label="排班方案" prop="schemeName">
                <el-input v-model="ruleForm.mainForm.schemeName" :disabled="typeId=='2'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排班类型" prop="classType">
                <el-radio-group v-model="ruleForm.mainForm.classType" :disabled="typeId=='2'" @change="changeClassType">
                  <el-radio
                    v-for="(item, index) in classTypeOptions.slice(1, classTypeOptions.length)"
                    :key="index"
                    :label="item.value">
                    {{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="排班班次" prop="schemeClasses">
                <div class="tagChose">
                  <el-tag v-for="tag in ruleForm.mainForm.schemeClasses" :key="tag.id"
                          style="margin-right: 10px;color:#606266"
                          :closable="typeId!='2'" :color="tag.color" @close="handleClose(tag)" :hit="false">
                    {{ tag.className }}
                  </el-tag>
                </div>
                <el-button type="primary" @click="selectClass" v-if="typeId!='2'">选择</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="排班模式" prop="schemeModel">
                <el-select v-model="ruleForm.mainForm.schemeModel" :disabled="typeId=='2'" placeholder="请选择"
                           style="width: 100%"
                           @change="modelChange">
                  <el-option
                    v-for="item in schemeModelOptions.slice(1, schemeModelOptions.length)"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排班周期" prop="schemeDate">
                <el-select v-model="ruleForm.mainForm.schemeDate" :disabled="typeId==='3'||typeId==='2'"
                           placeholder="请选择"
                           style="width: 100%"
                           @change="schemeDateChange">
                  <el-option
                    v-for="item in ruleForm.schemeDateOptions"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value">
                  </el-option>
                </el-select>
                <span v-if="schemeCopyDate == ruleForm.mainForm.schemeDate && typeId == '4'"
                      style="color: #f56c6c;position: absolute;top: 30px">
                  请更换排班周期！
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="打卡要求：" label-width="120px" style="display: flex; align-items: center"
                            prop="clockRequire">
                <el-checkbox v-model="ruleForm.mainForm.chekIn" :disabled="typeId==='2'" label="上班打卡" size="large"/>
                <el-checkbox v-model="ruleForm.mainForm.chekOut" :disabled="typeId==='2'" label="下班打卡"
                             size="large"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <el-table
        :data="ruleForm.schemeDetailTable"
        :min-height="'35rem'"
        style="width: 100%;border:1px solid #ebeef5;"
      >
        <el-table-column
          v-for="(item, index) in scheduleDetailTableColumns(ruleForm.mainForm.schemeDate)"
          :key="index"
          :min-width="item.minWidth"
          :fixed="item.fixed"
          :align="item.align"
        >
          <template #header>
            <div v-if="item.prop === 'name'&&typeId!=='2'">
              {{ item.label }}
              <el-icon @click="setPerson" style="cursor: pointer">
                <Plus/>
              </el-icon>
            </div>
            <div v-else-if="item.prop.indexOf('formatDate') > -1" class="header">
                <span v-if="ruleForm.holiday.get(item.day)"
                      class="holidayText"
                      :class="ruleForm.holiday.get(item.day)?.status === 0 ? 'holiday': 'work'">
                  {{ ruleForm.holiday.get(item.day)?.status === 0 ? '休' : '班' }}</span>
              <span v-else class="holidayText"></span>
              <span class="day" :style="{color: item.color ? item.color : '#909399'}">{{ item.label }}</span>
            </div>
            <span v-else>{{ item.label }}</span>
          </template>
          <template #default="scope">
            <span v-if="item.prop === 'name'">
              <el-icon style="cursor: pointer" @click="removePerson(scope.row)" v-if="typeId!=='2'"><Minus/></el-icon>{{
                scope.row[item.prop]
              }}</span>
            <span v-else-if="item.prop.indexOf('formatDate') < 0">{{ scope.row[item.prop] }}</span>
            <div v-else>
              <!--班次选择pop框-->
              <el-popover
                :visible="ruleForm.editSchedual.item?.prop === item?.prop && ruleForm.editSchedual.row === scope.row"
                placement="bottom"
                :title="typeId!=='1' ? null : '选择班次'"
                :width="ruleForm.mainForm.schemeModel==1?'15rem':'18rem'">
                <div v-if="typeId!=='1'">
                  <el-row>
                    <el-col :span="24">
                      <el-tabs v-model="ruleForm.tabActive">
                        <el-tab-pane label="更换班次" name="1">
                          <el-select v-model="ruleForm.editSchedual.classId" placeholder="请选择"
                                     style="margin-bottom: 10px">
                            <el-option
                              v-for="item in ruleForm.classDetailTableOptions"
                              :key="item.id"
                              :label="item.showText"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-tab-pane>
                        <el-tab-pane label="人员代班" name="2"
                                     v-if="scope.row.dailyDetailMap.get(item.prop)!=undefined">
                          <el-select v-model="ruleForm.editSchedual.substituteId" placeholder="请选择"
                                     v-if="ruleForm.mainForm.schemeModel==1">
                            <el-option
                              v-for="item in substituteArr"
                              :key="item.staffId"
                              :label="item.name"
                              :value="item.staffId">
                            </el-option>
                          </el-select>
                          <div style="position: absolute;font-size: 24px;top:0px;right:0;cursor: pointer"
                               v-if="ruleForm.mainForm.schemeModel!=1&&typeId !== '2'&&substituteArr.length>1"
                               @click="addMore(item, scope.row,index)">+
                          </div>
                          <div v-for="(mores,moresInx) in ruleForm.editSchedual.dbscheduleReqList"
                               style="display: flex;justify-content:flex-start;margin-top: 24px"
                               v-if="ruleForm.mainForm.schemeModel!=1">
                            <div
                              style="width:7.5rem;text-align: center;display: flex;flex-direction: column;margin-bottom: 10px">
                              <label>被代班人</label>
                              <el-select v-model="mores.schedulerId" placeholder="请选择">
                                <el-option
                                  v-for="item in teamsArr"
                                  :key="item.staffId"
                                  :label="item.name"
                                  :value="item.staffId"
                                  :disabled="item.disabled">
                                </el-option>
                              </el-select>
                            </div>
                            <div style="width:7.5rem;text-align: center;display: flex;flex-direction: column;margin-left: 10px">
                              <label>代班人</label>
                              <el-select v-model="mores.substituteId" placeholder="请选择">
                                <el-option
                                  v-for="item in substituteArr"
                                  :key="item.staffId"
                                  :label="item.name"
                                  :value="item.staffId"
                                  :disabled="item.disabled">
                                </el-option>
                              </el-select>
                            </div>
                            <div style="position: relative;font-size: 24px;top:18px;right:0;cursor: pointer"
                                 v-if="ruleForm.mainForm.schemeModel!=1&&typeId !== '2'&&substituteArr.length>1&&moresInx>0"
                                 @click="delMore(item, scope.row,moresInx)">-
                            </div>
                          </div>
                        </el-tab-pane>
                      </el-tabs>
                    </el-col>
                  </el-row>
                </div>
                <div style="height: 3rem;" v-else>
                  <el-row>
                    <el-col :span="24">
                      <el-select v-model="ruleForm.editSchedual.classId" placeholder="请选择">
                        <el-option
                          v-for="item in ruleForm.classDetailTableOptions"
                          :key="item.id"
                          :label="item.showText"
                          :value="item.id+''">
                        </el-option>
                      </el-select>
                    </el-col>
                  </el-row>
                </div>
                <div style="text-align: right; margin: 0">
                  <el-button @click="cancelSchedual()" v-if="typeId !== '2'">关闭</el-button>
                  <el-button type="primary" @click="saveSchedual(item, scope.row)" v-if="typeId !== '2'">确定
                  </el-button>
                </div>
                <template #reference>
                    <span class="schedualClass"
                          :style="{ backgroundColor: scope.row.dailyDetailMap.get(item.prop)?.color }"
                          @click="setSchedual(item, scope.row)">
                      <span v-if="scope.row.dailyDetailMap.get(item.prop)?.substituteId"
                            class="substituteText">代</span>
                      <span v-if="scope.row.dailyDetailMap.get(item.prop)?.clash"
                            class="clashText">冲突</span>
                      {{ scope.row.dailyDetailMap.get(item.prop)?.className }}
                    </span>
                </template>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex;position: absolute;bottom: 0;left:40%">
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" v-if="typeId !== '2'" v-loading="showSubmit" @click="submitForm(mainForm)">保存</el-button>
      </div>
    </div>
    <!--班次选择-->
    <el-dialog
      v-model="ruleForm.classDialogVisible"
      title="选择班次"
      width="30%"
      draggable
      align-center
      @closed="closedDialog"
    >
      <el-form>
        <el-form-item label="班次类型" prop="classType">
          <el-select v-model="ruleForm.mainForm.classType" disabled>
            <el-option
              v-for="item in classTypeOptions.slice(1, classTypeOptions.length)"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <table-common
          v-if="ruleForm.mainForm.classType==='S'"
          :columns="classDetailTableColumns"
          :table-data="ruleForm.classDetailTable"
          :pagination="false"
          ref="classTable"
          @select="handleSelect"
          :height="'300px'"
          @select-all="handleSelectAll"
        >
          <template #stime="{row}">
            <el-text>{{ row.stime ? row.stime : '-' }}</el-text>
          </template>
          <template #etime="{row}">
            <el-text>{{ row.etime ? row.etime : '-' }}</el-text>
          </template>
        </table-common>
        <table-common
          v-else
          :columns="classDetailTableColumnsOther"
          :table-data="ruleForm.classDetailTable"
          :pagination="false"
          :height="'300px'"
          ref="classTable"
          @mounted="classTableMounted"
          @select="handleSelect"
          @select-all="handleSelectAll"
        >
        </table-common>
      </el-form>
      <template #footer>
            <span class="dialog-footer">
              <el-button @click="ruleForm.classDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveClass">确定</el-button>
            </span>
      </template>
    </el-dialog>
    <!--人员选择-->
    <el-dialog
      v-model="ruleForm.personData.show"
      :title="ruleForm.personData.title"
      width="650px"
      draggable
      align-center
      v-loading="ruleForm.loading"
      @closed="cancelPerson"
    >
      <!--选择班组-->
      <CustomTransfer
        :filter-method="filterPerson"
        v-model="ruleForm.personData.selectPersons"
        :types="ruleForm.mainForm.schemeModel"
        :data="ruleForm.personData.personList"
        @change="changeValue"/>
      <template #footer>
              <span class="dialog-footer">
                <el-button @click="ruleForm.personData.show = false">取消</el-button>
                <el-button type="primary" :loading="showPersonLoading" @click="savePerson">确定</el-button>
              </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, defineExpose, onBeforeMount, onMounted } from 'vue'
import moment from 'moment'
import TableCommon from '@/components/TableCommon/index.vue'
import { classTypeOptions, schemeModelOptions } from './config/options'
import { classDetailTableColumns, classDetailTableColumnsOther, scheduleDetailTableColumns } from './config/columns'
import type { FormInstance, ElTable } from 'element-plus'

import { ElMessage } from 'element-plus'
import { rules } from './config/rules'
import { useRoute } from 'vue-router'
import {
  groupList,
  staffList,
  findSchedule,
  addScheduleScheme,
  detailScheduleScheme,
  updateScheduleScheme,
  isSchedule,
  getEmpNot,
  findEmployee
} from '@/api/quality/schedule'
import CustomTransfer from './components/customTransfer.vue'
import { scheduleGroupUpdate } from '@/api/quality/scheduleGroup'
import { getResource } from '@/api/resource'

interface Option {
  key: number
  label: string
}

const mainForm = ref<FormInstance>()
const classTable = ref<InstanceType<typeof TableCommon>>()
const classSelect = ref()
//面包屑动态字段
const programme = ref<string>('')
//获取路由
const router = useRoute()
//从路由里获取参数
const typeId = router.query.type
const nodeRowData = router.query.nodeRowData
const tableId = router.query.tableId
// 编辑页面的数据
const ruleForm = reactive({
  loading: false,
  editId: null,
  mainForm: {
    schemeName: null,
    classType: 'S',
    schemeClasses: ref<any>([]),
    schemeModel: 1,
    schemeDate: moment().format('YYYY-MM'),
    chekIn: null,
    chekOut: null,
  },
  schemeDateOptions: [{ // 排班周期选项
    value: moment().format('YYYY-MM')
  }, {
    value: moment().add(1, 'months').format('YYYY-MM')
  }, {
    value: moment().add(2, 'months').format('YYYY-MM')
  }],
  ruleOptions: ref<any>([]), // 排班规则
  classDialogVisible: false, // 班次选择显隐
  classDetailTable: ref<any>([]), // 详细班次数据
  classDetailTableOptions: ref<any>([]), // 可选的班次
  classDetailTableMap: new Map(), // 可选的班次map
  editSchedual: { // 编辑中的排班
    classId: null,
    item: null,
    row: null,
    substituteId: null,
    dbscheduleReqList: [{}],
  },
  schemeDetailTable: ref<any>([]), // 排班详情
  personData: {
    show: false,
    title: '选择人员',
    personList: ref<Option[]>(),
    personMap: new Map(),
    selectPersons: []
  },
  holiday: new Map(),
  tabActive: '1'
})
const show = ref<boolean>(false)
const title = ref<String>('')

const changeValue = (value: any) => {
  ruleForm.personData.selectPersons = value
}
// 初始化页面
const init = () => {
  Promise.all([
    findSchedule({ classType: ruleForm.mainForm.classType }),
    staffList({ createDept: nodeRowData }),
    groupList(nodeRowData),
  ]).then(([res1, res2, res3]) => {
    if (res1.code === '1') {
      ruleForm.classDetailTable = []
      res1.data.forEach((item: any) => {
        let classDetail = JSON.parse(eval('(' + item.classDetail + ')'))
        item.stime = classDetail.date[0]
        item.etime = classDetail.date[1]
      })
      if (typeId != '1') {
        res1.data.push({
          className: '休息',
          color: '#cdcdcd',
          id: '0'
        })
      }
      ruleForm.classDetailTable = res1.data
      loadSelectClass()
    }
    if (ruleForm.mainForm.schemeModel === 1) {
      ruleForm.personData.title = '选择人员'
      if (res2.code === '1') {
        res2.data.forEach((item: any) => {
          item.isDisabled = false
          item.label = item.name
          item.id = item.staffId
          item.children = item.children || []
        })
        ruleForm.personData.personList = res2.data || []
      }
    } else {
      ruleForm.personData.title = '选择班组'
      if (res3.code == '1') {
        ruleForm.personData.personList = deepFn(res3.data) || []
      }
    }
    if (typeId !== '1') {
      intDetail()
    }
  })
}
const fullscreenLoading = ref(false)
const schemeCopyDate = ref('')
const detailPerson = ref([])
const ruleFormSchemeDetailTable = ref([])

// 添加代班人员租
const addMore = (item, row, index) => {
  row.dailyDetailMap?.get(item.prop)?.dbscheduleReqList.push({})
}
const delMore = (item, row, moresInx) => {
  ruleForm.editSchedual.dbscheduleReqList.splice(moresInx,1)
}

// 设置默认数据
const intDetail = async () => {
  fullscreenLoading.value = true
  const resp = await detailScheduleScheme(tableId)
  if (resp.code === '1') {
    let {
      schemeName,
      classType,
      schemeClasses,
      schemeModel,
      schemeDate,
      chekIn,
      chekOut,
      qualityScheduleDetailList
    } = resp.data
    schemeCopyDate.value = schemeDate
    let schemeArrs = schemeClasses.split(',')
    let schemeObjArrs = []
    ruleForm.classDetailTable.forEach((itemDetail) => {
      schemeArrs.forEach((schemeItem) => {
        if (schemeItem == itemDetail.id) {
          schemeObjArrs.push(itemDetail)
        }
      })
    })
    ruleForm.mainForm = {
      schemeName,
      classType,
      schemeClasses: schemeObjArrs,
      schemeModel,
      schemeDate,
      chekIn: chekIn === 1 ? true : false,
      chekOut: chekOut === 1 ? true : false,
    }
    if (ruleForm.personData.personList != undefined) {
      let schemeDetailTable = []
      let personDataPersonList = []
      if (schemeModel === 1) {
        personDataPersonList = ruleForm.personData.personList
      } else {
        personDataPersonList = filterTreeArray(JSON.parse(JSON.stringify(ruleForm.personData.personList)))
      }
      personDataPersonList.forEach((personItem) => {
        let personArr = []
        qualityScheduleDetailList.forEach((itemList) => {
          let showId = 0
          if (schemeModel == 1) {
            showId = itemList.schedulerId
          } else {
            showId = itemList.teamId
          }
          if (personItem.id == showId) {
            personArr.push({
              personItem,
              ...itemList
            })
          }
        })
        if (personArr.length !== 0) {
          let dailyDetailMaps = new Map()
          personArr.forEach((personResp) => {
            dailyDetailMaps.set('formatDate' + personResp.scheduleDate, {
              scheduleDate: personResp.scheduleDate,
              classId: personResp.classId,
              className: personResp.classesName,
              color: personResp.color,
              substituteId: personResp.substituteId,
              dbscheduleReqList: personResp.dbscheduleReqList.length === 0 ? [{}] : personResp.dbscheduleReqList,
              classTime: [personResp.officeHours, personResp.closingTime],
              teamId: personResp.teamId,
              workDay: 1
            })
          })
          schemeDetailTable.push({
            name: personArr[0].personItem.name,
            id: personArr[0].personItem,
            teamId: personArr[0].teamId,
            countWork: personArr[0].countWork,
            countPlan: personArr[0].countPlan,
            dailyDetailMap: dailyDetailMaps,
            dailyDetail: []
          })
        }
      })
      ruleForm.schemeDetailTable = schemeDetailTable
      ruleFormSchemeDetailTable.value = schemeDetailTable
      // schemeDetailTable.forEach((detailTableItem)=>{
      //   detailPerson.value.push(detailTableItem.id)
      // })
    }
    fullscreenLoading.value = false
  }
}
//展开树状图
const filterTreeArray = (array: any) => {
  let newData: any[] = []
  const callback = (item: any) => {
    (item.children || (item.children = [])).map((v: any) => {
      callback(v)
    })
    delete item.children
    newData.push(item)
  }
  array.map((v: any) => callback(v))
  return newData
}
const  showSubmit=ref(false)
// 保存按钮触发事件
const submitForm = (formEl: FormInstance | undefined) => {
  showSubmit.value=true
  mainForm.value.validate((valid) => {
    if (valid) {
      let {
        schemeDate,
        classType,
        schemeModel,
        schemeName,
        schemeClasses,
        chekIn,
        chekOut
      } = ruleForm.mainForm
      if (schemeCopyDate.value == schemeDate && typeId == '4') {
        ElMessage.warning('请更换排班周期！')
        return
      }
      let arrs = []
      schemeClasses.forEach((item) => {
        arrs.push(item.id)
      })
      let arrTwo = []
      ruleForm.schemeDetailTable.forEach((item: any) => {
        item.dailyDetailMap.forEach((value, key) => {
          let arr = []
          if (value.dbscheduleReqList != undefined) {
            value.dbscheduleReqList.forEach((item) => {
              if (JSON.stringify(item) != '{}') {
                arr.push(item)
              }
            })
          } else {
            value.dbscheduleReqList = []
          }
          arrTwo.push({
            ...value,
            classesName: value.className,
            countPlan: item.countPlan,
            countWork: item.countWork,
            schemeDate,
            classesType: classType,
            officeHours: value.classTime[0],
            closingTime: value.classTime[1],
            createDept: nodeRowData,
            scheduleDate: value.scheduleDate,
            schedulerId:isConfirm.value?item.id.staffId:'',
            dbscheduleReqList: arr,
            name: item.name,
            teamId: item.id.id,
          })
        })
      })
      let parem = {
        chekIn: chekIn ? 1 : 0,
        chekOut: chekOut ? 1 : 0,
        classType,
        deptId: nodeRowData,
        qualityScheduleDetailList: arrTwo,
        schemeClasses: arrs.join(','),
        schemeDate,
        schemeModel,
        schemeName,
        schemeRule: null,
      }
      if (typeId == '1' || typeId == '4') {
        addScheduleScheme(parem).then(resp => {
          if (resp.code === '1') {
            showSubmit.value=false
            ElMessage.success('新增成功！')
            window.history.go(-1)
          }
        })
      } else if (typeId == '3') {
        parem.id = tableId
        updateScheduleScheme(parem).then(resp => {
          if (resp.code === '1') {
            showSubmit.value=false
            ElMessage.success('编辑成功！')
            window.history.go(-1)
          }
        })
      }
    } else {
      return
    }
  })
}

const handleClose = (tag: string) => {
  ruleForm.mainForm.schemeClasses.splice(ruleForm.mainForm.schemeClasses.indexOf(tag), 1)
}
// 给表格设置选中
const classTableMounted = () => {
  selectClass()
}
const selectArr = ref([])
const handleSelect = (selection: any) => {
  selectArr.value = selection
}
const handleSelectAll = (selection: any) => {
  selectArr.value = selection
}
const changeClassType = () => {
  ruleForm.mainForm.schemeClasses = []
  ruleForm.schemeDetailTable = ref<any>([])
  ruleForm.personData.selectPersons = []
}
// 加载可选的排班
const loadSelectClass = () => {
  ruleForm.classDetailTableOptions = []
  ruleForm.classDetailTableMap.clear()
  ruleForm.mainForm.schemeClasses?.forEach((c: any) => {
    ruleForm.classDetailTable.forEach((r: any) => {
      if (c.id === r.id) {
        r.showText = r.className
        if (r.classType === 'S') {
          r.showText += '(' + r.stime + '~' + r.etime + ')'
        }
        ruleForm.classDetailTableOptions.push(r)
        ruleForm.classDetailTableMap.set(r.id, r)
      }
    })
  })
}
// 选择班次
const selectClass = () => {
  ruleForm.mainForm.schemeClasses?.forEach((c: any) => {
    ruleForm.classDetailTable.forEach((row: any) => {
      if (c.id === row.id) {
        classTable.value?.tableInstance?.toggleRowSelection(row, true)
      }
    })
  })
  ruleForm.classDialogVisible = true
}
// 确定班次选择
const saveClass = () => {
  if (typeId == '1') {
    selectArr.value.push({
      className: '休息',
      color: '#cdcdcd',
      id: '0'
    })
  }
  ruleForm.mainForm.schemeClasses = newArrFn(selectArr.value)
  ruleForm.classDialogVisible = false
}
const newArrFn = (arr) => {
  const res = new Map()
  return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, arr.id))
}
// 关闭班次选择框
const closedDialog = () => {
  classTable.value.tableInstance?.clearSelection()
}
//递归添加标识
const deepFn = (data = []) => {
  data.forEach((item: any) => {
    if (item.children !== null) {
      item.isDisabled = true
      item.label = item.name
      item.children = item.children || []
      deepFn(item.children)
    } else {
      item.isDisabled = false
      item.label = item.name
      item.children = item.children || []
    }
  })
  return data
}
// 选择人员/班组
const setPerson = () => {
  ruleForm.personData.show = true
}
// 关闭人员/班组选择
const cancelPerson = () => {
  ruleForm.personData.show = false
}
const showPersonLoading = ref(false)
// 保存人员/班组选择
const savePerson = () => {
  let personsIdArr = []
  ruleForm.personData.selectPersons.forEach((p: Option) => {
    personsIdArr.push(p.id)
  })
  showPersonLoading.value = true
  isSchedule(ruleForm.mainForm.schemeModel, ruleForm.mainForm.schemeDate, personsIdArr.join(',')).then(resp => {
    if (resp.code === '1') {
      if (resp.data.length === 0) {
        ruleForm.schemeDetailTable = []
        ruleForm.personData.selectPersons.forEach((p: Option) => {
          ruleForm.schemeDetailTable.push({
            id: p,
            name: p.label,
            countWork: 0,
            countPlan: 0,
            dailyDetailMap: new Map(),
            dailyDetail: []
          })
          ruleForm.schemeDetailTable.forEach((item) => {
            if (item.id.staffId == p.staffId) {
              if (p.dailyDetailMap !== undefined) {
                item.dailyDetailMap = p.dailyDetailMap
                p.dailyDetailMap.forEach((seeValue) => {
                  if (seeValue.classTime != undefined) {
                    let dayTime = ruleForm.mainForm.schemeDate + '-' + seeValue.scheduleDate
                    let hores = timediff(dayTime + ' ' + seeValue.classTime[0], dayTime + ' ' + seeValue.classTime[1])
                    item.countPlan += hores
                    item.countPlan = Number(item.countPlan.toFixed(1))
                  } else {
                    item.countPlan = 0
                  }
                })
              } else {
                item.dailyDetailMap = new Map()
              }
            }
          })
        })
        if (typeId != '1') {
          ruleForm.schemeDetailTable.unshift(...ruleFormSchemeDetailTable.value)
        }
        cancelPerson()
      } else {
        let messageArr = []
        resp.data.forEach((item) => {
          let personDataPersonList = []
          if (ruleForm.mainForm.schemeModel === 1) {
            personDataPersonList = ruleForm.personData.personList
          } else {
            personDataPersonList = filterTreeArray(JSON.parse(JSON.stringify(ruleForm.personData.personList)))
          }
          personDataPersonList.forEach((respRow) => {
            if (item.schedulerORteamId == respRow.id) {
              messageArr.push(respRow.name)
            }
          })
        })
        ElMessage.error(messageArr.join(',') + '在' + ruleForm.mainForm.schemeDate + '月，已存在排班')
        cancelPerson()
      }
      showPersonLoading.value = false
    }
  })

}
// 人员过滤
const filterPerson = (query: string, item: Option) => {
  return item.label.toLowerCase().includes(query.toLowerCase())
}
// 移除排班人员
const removePerson = (row: any) => {
  ruleForm.personData.selectPersons.splice(ruleForm.personData.selectPersons.indexOf(row.id, 1))
  ruleForm.schemeDetailTable.splice(ruleForm.schemeDetailTable.indexOf(row), 1)
}
// 排班详情选择班次
const setSchedual = (item: any, row: any) => {
  ruleForm.editSchedual.item = item
  ruleForm.editSchedual.row = row
  ruleForm.editSchedual.classId = row.dailyDetailMap?.get(item.prop)?.classId
  ruleForm.editSchedual.substituteId = row.dailyDetailMap?.get(item.prop)?.substituteId
  ruleForm.editSchedual.dbscheduleReqList = row.dailyDetailMap?.get(item.prop)?.dbscheduleReqList
  if (typeId != '1') {
    substituteClass()
    teamsClass()
  }
}
// 取消排班详情班次选择
const cancelSchedual = () => {
  ruleForm.editSchedual.item = null
  ruleForm.editSchedual.classId = null
  ruleForm.editSchedual.row = null
}
const  isConfirm=ref(false)
// 保存排班详情班次选择
const saveSchedual = (item: any, row: any) => {
  const thisClass = ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)
  if (thisClass.id !== '0' && ruleForm.tabActive == '1') {
    if (ruleForm.mainForm.classType === 'S') {
      schedulingData(item, row)
    } else if (ruleForm.mainForm.classType === 'F') {
      fixedClass(item, row)
    } else {
      shiftSystem(item, row)
    }
  } else {
    let substituteDataArrs = []
    if (ruleForm.editSchedual.dbscheduleReqList != undefined) {
      ruleForm.editSchedual.dbscheduleReqList.forEach((otherResp) => {
        let node = {
          schedulerId: otherResp.schedulerId,
          substituteId: otherResp.substituteId,
          scheduleDate: item.day,
        }
        substituteDataArrs.push(node)
      })
    }
    let substituteId = ''
    if (ruleForm.editSchedual.substituteId != undefined || ruleForm.editSchedual.dbscheduleReqList != undefined) {
      substituteId = ruleForm.editSchedual.substituteId || substituteDataArrs[0].schedulerId
    }
    row.dailyDetailMap.set('formatDate' + item.day, {
      scheduleDate: item.day,
      classId: ruleForm.editSchedual.classId,
      className: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.className,
      color: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.color,
      substituteId: substituteId,
      dbscheduleReqList: substituteDataArrs,
      classTime: ['00:00', '00:00'],
      workDay: 1
    })
  }
  row.countPlan = 0
  ruleForm.schemeDetailTable.forEach((seeSchemeDeta) => {
    seeSchemeDeta.dailyDetailMap.forEach((seeValue) => {
      if (seeSchemeDeta.id.id === row.id.id) {
        if (seeValue.classTime != undefined) {
          let dayTime = ruleForm.mainForm.schemeDate + '-' + item.day
          let hores = timediff(dayTime + ' ' + seeValue.classTime[0], dayTime + ' ' + seeValue.classTime[1])
          row.countPlan += hores
          row.countPlan = Number(row.countPlan.toFixed(1))
        }
      }
    })
  })
  ruleForm.personData.selectPersons.forEach((item) => {
    if (item.staffId == row.id.staffId) {
      item.dailyDetailMap = row.dailyDetailMap
    }
  })
  isConfirm.value=true
  cancelSchedual()
}
// 排版制
const schedulingData = (item: any, row: any) => {
  const thisClass = ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)
  let classDetail = JSON.parse(eval('(' + thisClass.classDetail + ')'))
  row.dailyDetailMap.set('formatDate' + item.day, {
    scheduleDate: item.day,
    classId: ruleForm.editSchedual.classId,
    className: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.className,
    color: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.color,
    substituteId: ruleForm.editSchedual.substituteId,
    dbscheduleReqList: ruleForm.editSchedual.dbscheduleReqList,
    classTime: classDetail.date,
    workDay: 1
  })
}
// 固定班制度
const fixedClass = (item: any, row: any) => {
  const thisClass = ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)
  let classDetail = JSON.parse(eval('(' + thisClass.classDetail + ')'))
  let classDetailDate = []
  classDetail.date.forEach((itemDates: any) => {
    if (itemDates.dateStr != ''&&itemDates.dateStr != null&&itemDates.dateStr != undefined) {
      classDetailDate.push(itemDates)
    }
  })
  row.dailyDetailMap = new Map()
  let columnsData = scheduleDetailTableColumns(ruleForm.mainForm.schemeDate)
  let spliceColumnsData = columnsData.splice(3, columnsData.length)
  spliceColumnsData.forEach((itemColumns: any) => {
    if (classDetailDate.length !== 0) {
      classDetailDate.forEach((classDate) => {
        if (itemColumns.weekDayTxt === classDate.dayText) {
          if (classDate.dateStr != '') {
            row.dailyDetailMap.set('formatDate' + itemColumns.day, {
              scheduleDate: itemColumns.day,
              classId: ruleForm.editSchedual.classId,
              className: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.className,
              color: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.color,
              substituteId: ruleForm.editSchedual.substituteId,
              dbscheduleReqList: ruleForm.editSchedual.dbscheduleReqList,
              classTime: classDate.dateStr,
              workDay: 1
            })
          } else {
            row.dailyDetailMap.set('formatDate' + itemColumns.day, {
              scheduleDate: itemColumns.day,
              className: '休息',
              color: '#cdcdcd',
              id: '0'
            })
          }
        }
      })
    }
  })
}
//轮班制度
const shiftSystem = (item: any, row: any) => {
  const thisClass = ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)
  let classDetail = JSON.parse(eval('(' + thisClass.classDetail + ')'))
  row.dailyDetailMap = new Map()
  let columnsData = scheduleDetailTableColumns(ruleForm.mainForm.schemeDate)
  let spliceColumnsData = columnsData.splice(3, columnsData.length)
  let loopNum = 1
  spliceColumnsData.forEach((itemColumns: any, index: number) => {
    if (parseInt(classDetail.date.workDay) >= loopNum) {
      row.dailyDetailMap.set('formatDate' + itemColumns.day, {
        scheduleDate: itemColumns.day,
        classId: ruleForm.editSchedual.classId,
        className: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.className,
        color: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.color,
        substituteId: ruleForm.editSchedual.substituteId,
        dbscheduleReqList: ruleForm.editSchedual.dbscheduleReqList,
        classTime: classDetail.date.dateList[loopNum - 1].date,
        workDay: 1
      })
    } else {
      let loopAllDay = parseInt(classDetail.date.workDay) + parseInt(classDetail.date.restDay)
      if (loopNum >= loopAllDay) {
        loopNum = 0
      }
    }
    loopNum++
  })
}
//计算时间差
const timediff = (beginTime, endTime) => {
  //年月日时分秒转换为时间戳
  let beginTimes = (new Date(beginTime).getTime()) / 1000
  let endTimes = (new Date(endTime).getTime()) / 1000
  var starttime = ''
  var endtime = ''
  if (beginTimes < endTimes) {
    starttime = beginTimes
    endtime = endTimes
  } else {
    starttime = endTimes
    endtime = beginTimes
  }
  //计算天数
  var timediff = endtime - starttime
  //计算小时数
  var remain = timediff % 86400
  var hours = Number((remain / 3600).toFixed(1))

  return hours
}
// 冲突验证，row:detailMap里需要验证的一条，id：排班对象的ID
const clash = (row: any, id: string) => {
  const param = {
    schemeId: null,
    classId: ruleForm.editSchedual.classId,
    schemeDate: ruleForm.mainForm.schemeDate,
    scheduleDate: row.scheduleDate,
    schemeObj: id,
  }
  if (ruleForm.editId) {
    param.schemeId = ruleForm.editId
  }
  // clashJuge(param).then((res: { code: string; data: any }) => {
  //   if (res.code === '1') {
  //     if (res.data) {
  //       row.clash = true
  //     } else {
  //       row.clash = false
  //     }
  //   }
  // })
}
const substituteArr = ref([])
const teamsArr = ref([])

// 获取代班人是否有班次
const substituteClass = () => {
  let lastDay = ruleForm.editSchedual.item.day < 10 ? '0' + ruleForm.editSchedual.item.day : ruleForm.editSchedual.item.day
  let day = ruleForm.mainForm.schemeDate + '-' + lastDay
  getEmpNot(day, nodeRowData).then(resp => {
    if (resp.code == '1') {
      let moreSubstitute = []
      ruleForm.editSchedual.row.dailyDetailMap.forEach((vals) => {
        vals.dbscheduleReqList.forEach((resps) => {
          moreSubstitute.push(resps.substituteId)
        })
      })
      resp.data.forEach((moresItme) => {
        moreSubstitute.forEach((itemsAll) => {
          if (moresItme.staffId == itemsAll) {
            moresItme.disabled = true
          }
        })
      })
      substituteArr.value = resp.data
    }
  })
}
//获取被代班人
const teamsClass = () => {
  findEmployee({
    groupId: ruleForm.editSchedual.row.teamId,
  }).then(resp => {
    if (resp.code == '1') {
      teamsArr.value = resp.data
    }
  })
}
// 排班模式变更
const modelChange = () => {
  ruleForm.personData.selectPersons = []
  ruleForm.schemeDetailTable = []
}
// 排班周期变更
const schemeDateChange = () => {
  ruleForm.schemeDetailTable = ruleFormSchemeDetailTable
}
watch(() => ruleForm.mainForm.schemeClasses, () => {
  loadSelectClass()
})
watch(() => [ruleForm.mainForm.schemeModel,ruleForm.mainForm.classType], (newValue,oldValue)=>{
  if(newValue[0]!=oldValue[0]||newValue[1]!=oldValue[1]){
    init()
  }
})
onBeforeMount(init)
onMounted(() => {
  switch (typeId) {
    case '1':
      programme.value = '新增排班方案'
      break
    case '2':
      programme.value = '查看排班方案'
      break
    case '3':
      programme.value = '编辑排班方案'
      break
  }
})
</script>

<style lang="less" scoped>

//@import "../style/publicStyle.less";
/deep/ .el-table .cell {
  white-space: pre-line !important;
  text-align: center;
}

.header {
  display: flex;
  justify-content: space-between;
  flex-direction: column;

  .holidayText {
    width: 1rem;
    height: 1rem;
    line-height: 1rem;
    font-size: 12px;
    font-weight: normal;
    color: white;
    border-radius: 0.2rem;

    &.holiday {
      background-color: #9fd546;
    }

    &.work {
      background-color: #f0514c;
    }
  }
}

/deep/ .el-input__suffix {
  display: none;
}

.el-breadcrumb {
  padding: 12px 24px;
  line-height: 22px;
}

/deep/ .el-breadcrumb__inner {
  color: #989DAA;
}

.container {
  .tableColumns {
    height: 810px;
    flex-direction: column;
    background-color: #FFFFFF;
    margin: 0 15px;
    padding: 12px 24px;
    border-radius: 5px;
    position: relative;

    .addProgramme {
      height: 280px;
    }

    .realTimeProgramme {
      height: 550px;
    }

    .title-span {
      margin-top: 15px;
    }


    .content {
      width: 90%;
      margin: 10px auto;

      .tagChose {
        border-radius: 5px;
        height: 33px;
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        padding: 0 10px;
        width: 80%;
        margin-right: 20px
      }
    }

    .schedualClass {
      display: inline-block;
      position: relative;
      width: 100%;
      height: 2rem;
      line-height: 2rem;
      color: #000;
      cursor: pointer;
      border-radius: 0.5rem;
    }

    .substituteText {
      display: inline-block;
      position: absolute;
      top: 0;
      left: 0;
      width: 1rem;
      height: 1rem;
      line-height: 1rem;
      background-color: #81d3f8;
      border-radius: 0.2rem;
      font-size: 0.7rem;
    }

    .clashText {
      display: inline-block;
      position: absolute;
      top: 0;
      right: 0;
      width: 2rem;
      height: 1rem;
      line-height: 1rem;
      background-color: #d9001b;
      border-radius: 0.2rem;
      font-size: 0.7rem;
    }
  }

  .schedulingCalendar {
    height: 400px;
    margin: 0 35px;
  }

  .btnBox {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 35px;
  }
}


</style>
